// 预约数据
let appointments=[]
 appointments=JSON.parse(localStorage.getItem('bookingHistory')) ? JSON.parse(localStorage.getItem('bookingHistory')) : [];
// console.log("预约信息:",appointments);

//获得当前登录用户信息
let currentUser = localStorage.getItem('currentUser');
var element = document.getElementById('title')
// 如果有用户信息，解析并显示欢迎信息
if (currentUser) {
    currentUser = JSON.parse(currentUser);
    console.log(currentUser.name);
    
    element.innerHTML = "欢迎，" + currentUser.name + "！这是您的预约页面。";
}


// DOM元素
//展示预约信息的
const appointmentsContainer = document.getElementById('appointmentsContainer');
//查看预约详情的模态框
const viewModal = document.getElementById('viewModal');
//删除预约的模态框
const deleteModal = document.getElementById('deleteModal');
//预约详情内容
const appointmentDetails = document.getElementById('appointmentDetails');
//确认删除按钮
const confirmDeleteBtn = document.getElementById('confirmDelete');
// 当前选中的预约ID
let currentAppointmentId = null;

// 初始化页面
document.addEventListener('DOMContentLoaded', function() {
    renderAppointments();
    setupEventListeners();
});

// 渲染预约列表
function renderAppointments() {
    appointmentsContainer.innerHTML = '';
    if (appointments.length === 0) {
        appointmentsContainer.innerHTML = `
            <div class="empty-state">
                <i class="fas fa-calendar-times"></i>
                <p>暂无预约记录</p>
            </div>
        `;
        return;
    }
    //循环渲染数据
    appointments.forEach((appointment,index) => {
        appointment = JSON.parse(appointment); // 确保每个预约对象是正确的格式
        //创建div元素
        const appointmentItem = document.createElement('div');
        //设置类名和内容
        appointmentItem.className = 'appointment-item';

        appointmentItem.innerHTML = `
            <div><span class="appointment-type">${appointment.destination}</span></div>
            <div class="">${appointment.guests}</div>
            <div><span class="status"> ${appointment.arrivalDate}</span></div>
            <div><span class="status"> ${appointment.departureDate}</span></div>
            <div class="actions-cell">
                <button class="action-btn view" data-id="${index}">
                    <i class="fas fa-eye"></i>
                </button>
                <button class="action-btn delete" data-id="${index}">
                    <i class="fas fa-trash-alt"></i>
                </button>
            </div>
        `;
        //放到容器中
        appointmentsContainer.appendChild(appointmentItem);
    });
}

// 设置事件监听
function setupEventListeners() {
    // 查看预约详情
    document.querySelectorAll('.action-btn.view').forEach(btn => {
        btn.addEventListener('click', function() {
            const id = parseInt(this.getAttribute('data-id'));
            console.log('预约ID:', id);
            showAppointmentDetails(id);
        });
    });
    
    // 删除预约
    document.querySelectorAll('.action-btn.delete').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.stopPropagation();
            const id = parseInt(this.getAttribute('data-id'));
            console.log('预约ID:', id);
            showDeleteConfirmation(id);
        });
    });
    
    // 关闭模态框
    document.querySelectorAll('.close-btn, .close-modal').forEach(btn => {
        btn.addEventListener('click', closeAllModals);
    });
    
    // 确认删除
    confirmDeleteBtn.addEventListener('click', deleteAppointment);
    
    // 点击模态框外部关闭
    [viewModal, deleteModal].forEach(modal => {
        modal.addEventListener('click', function(e) {
            if (e.target === this) {
                closeAllModals();
            }
        });
    });
}

// 显示预约详情
function showAppointmentDetails(id) {
    const appointment = JSON.parse (appointments[id]);
    if (!appointment) return;
    console.log(currentUser);
    
    appointmentDetails.innerHTML = `
        <div class="detail-row">
            <div class="detail-label">预约人</div>
            <div class="detail-value">${currentUser.name}</div>
        </div>
        <div class="detail-row">
            <div class="detail-label">目的地</div>
            <div class="detail-value">${appointment.destination}</div>
        </div>
        <div class="detail-row">
            <div class="detail-label">出发时间</div>
            <div class="detail-value">${appointment.arrivalDate}</div>
        </div>
        <div class="detail-row">
            <div class="detail-label">返回时间</div>
            <div class="detail-value">${appointment.departureDate}</div>
        </div>
    `;
    
    viewModal.classList.add('active');
}

// 显示删除确认
function showDeleteConfirmation(id) {
    currentAppointmentId = id;
    deleteModal.classList.add('active');
}

// 删除预约
function deleteAppointment() {
    appointments.splice(currentAppointmentId, 1);
    // 更新本地存储
    console.log(appointments);
    
    localStorage.setItem('bookingHistory', JSON.stringify(appointments));
    renderAppointments();
    closeAllModals();
    showToast('预约已删除', 'success');
}

// 关闭所有模态框
function closeAllModals() {
    viewModal.classList.remove('active');
    deleteModal.classList.remove('active');
    currentAppointmentId = null;
}

// 辅助函数：格式化日期
function formatDate(dateString) {
    const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'short' };
    return new Date(dateString).toLocaleDateString('zh-CN', options);
}

// 辅助函数：获取状态文本
function getStatusText(status) {
    const statusMap = {
        'confirmed': '已确认',
        'pending': '待确认',
        'cancelled': '已取消'
    };
    return statusMap[status] || status;
}

// 显示Toast通知
function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.textContent = message;
    document.body.appendChild(toast);
    
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);
    
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            toast.remove();
        }, 300);
    }, 3000);
}